package com.px.framework.mqtt;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.px.common.core.redis.RedisCache;
import com.px.common.utils.DateUtils;
import com.px.system.domain.*;
import com.px.system.domain.dto.LiveCapacity;
import com.px.system.domain.vo.PushMqVo;
import com.px.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import static com.px.framework.mqtt.model.TopicConst.*;

@Service
public class MqttServiceServiceImpl {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MqttCustomerClient mqttCustomerClient;

    @Autowired
    private TaskRecordMediaMapper taskRecordMediaMapper;

    @Autowired
    private DroneInfoMapper droneInfoMapper;

//    @Autowired
//    private PlanActionRecordOsdMapper planActionRecordOsdMapper;

//    @Autowired
//    private PlanActionRecordMediaMapper planActionRecordMediaMapper;


//    @Autowired
//    private AirportOsdMapper airportOsdMapper;

    private static String url = "https://restapi.amap.com/v3/assistant/coordinate/convert?";

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${gaode.key}")
    private String gaodeKey;


    public void thingRequests(CommonTopic readValue, String sn) {
        /***
         * 机场获取上传凭证storage_config_get
         */
        if("storage_config_get".equals(readValue.getMethod())){
            //返回minio存储信息
            readValue.setTimestamp(DateUtils.getNowDate().getTime());
            JSONObject data = new JSONObject();
            data.put("result",0);
            JSONObject output = new JSONObject();
            output.put("bucket",bucketName);//桶名称
            output.put("endpoint",endpoint);//访问地址
            output.put("object_key_prefix","");//对象存储桶的key的前缀
            output.put("provider","minio");//云厂商枚举值
            output.put("region","hz");//数据中心所在的地域
            JSONObject credentials = new JSONObject();
            credentials.put("access_key_id",accessKey);//访问密钥ID
            credentials.put("access_key_secret",secretKey);//秘密访问密钥
            credentials.put("expire",7200);//访问密钥过期时间
            credentials.put("security_token","security_token");//会话凭证
            output.put("credentials",credentials);//凭证信息
            data.put("output",output);
            readValue.setData(data);
            String topic = THING_MODEL_PRE + PRODUCT + sn + REQUESTS_SUF + _REPLY_SUF;
            mqttCustomerClient.pushlish(topic,readValue.toString());
        }

    }

    public void thingEvents(CommonTopic readValue, String sn) {
        /***
         * 媒体文件上传结果上报Method: file_upload_callback.
         * 
         */
        if("file_upload_callback".equals(readValue.getMethod())){
            //上传文件存储，返回收到
            JSONObject file = readValue.getData().getJSONObject("file");
            String path = file.get("path").toString();
            String name = file.get("name").toString();
            String flightId = file.getJSONObject("ext").get("flight_id").toString();
            //根据计划id存库
            String url = endpoint + "/" + bucketName + "/" + path + "/" + name;
            JSONObject metadata = file.getJSONObject("metadata");
            Object createdTime = metadata.get("created_time");
            BigDecimal lat = metadata.getJSONObject("shoot_position").getBigDecimal("lat");
            BigDecimal lng = metadata.getJSONObject("shoot_position").getBigDecimal("lng");

            TaskRecordMedia taskRecordMedia = new TaskRecordMedia();
            taskRecordMedia.setRecordId(Long.valueOf(flightId));
            taskRecordMedia.setMediaType(1);
            taskRecordMedia.setMediaUrl(url);
            taskRecordMedia.setLongitude(lat);
            taskRecordMedia.setLatitude(lng);
            taskRecordMedia.setCreateTime(DateUtils.parseDate(createdTime));
            taskRecordMediaMapper.insertTaskRecordMedia(taskRecordMedia);
            readValue.setTimestamp(DateUtils.getNowDate().getTime());
            JSONObject data = new JSONObject();
            data.put("result",0);
            readValue.setData(data);
            String topic = THING_MODEL_PRE + PRODUCT + sn + REQUESTS_SUF + _REPLY_SUF;
            mqttCustomerClient.pushlish(topic,readValue.toString());
        }
    }

    //行动通知
    public void pushMq(PushMqVo pushMqVo) {
        JSONObject topic = new JSONObject();
        topic.put("type", pushMqVo.getType());
        topic.put("sn", pushMqVo.getSn());
        topic.put("timestamp",DateUtils.getNowDate().getTime());
        topic.put("data", pushMqVo.getData());
        mqttCustomerClient.pushDev(pushMqVo.getUserName(),topic.toJSONString());
    }

    public void pushPalnMq(PushMqVo pushMqVo) {
        JSONObject topic = new JSONObject();
        topic.put("type", pushMqVo.getType());
        topic.put("sn", pushMqVo.getSn());
        topic.put("timestamp",DateUtils.getNowDate().getTime());
        topic.put("data", pushMqVo.getData());
        mqttCustomerClient.pushPalnMq(pushMqVo.getPalnId(),topic.toJSONString());
    }

    //处理飞行器发送的消息
    public void appServices(PushMqVo pushMqVo) {
        /***
         * 设备上下线
         * 行动中的飞行器位置
         * 行动产生的图片视频
         */
        switch (pushMqVo.getType()){
            case SERVICES_DRONE_STATUS :
                /***
                 * 设备上下线通知
                 */
                DroneInfo droneInfo = new DroneInfo();
                droneInfo.setDutyCode(pushMqVo.getUserName());
                droneInfo.setSn(pushMqVo.getSn());
                droneInfo.setDroneState(pushMqVo.getData().getInteger("DroneState"));
//                droneInfoMapper.updateDroneStateInfoBySn(droneInfo);
                if(1 == pushMqVo.getData().getInteger("DroneState")){
                    droneInfoMapper.updateDroneStateInfoBySn(droneInfo);
                }else {
                    droneInfoMapper.updateDroneStateInfoByUserName(droneInfo);
                }

                break;
            default:

                break;
        }

    }


//    public void appPlanServices(PushMqVo pushMqVo) {
//        /***
//         * 设备上下线
//         * 行动中的飞行器位置
//         * 行动产生的图片视频
//         */
//        switch (pushMqVo.getType()){
//            case SERVICES_DRONE_ADDRESS :
//                /***
//                 * 经纬度位置，时间
//                 */
//                PlanActionRecordOsd planActionRecordOsd = new PlanActionRecordOsd();
//                planActionRecordOsd.setDroneSn(pushMqVo.getSn());
//                planActionRecordOsd.setRecordId(pushMqVo.getData().getLong("RecordId"));
//                Map<String ,Object> map  = new HashMap<>();
//                BigDecimal longitude = pushMqVo.getData().getBigDecimal("longitude");
//                BigDecimal latitude = pushMqVo.getData().getBigDecimal("latitude");
//                //gps坐标转高德坐标
////                String gaodeData = HttpUtil.get(url + "key=" + gaodeKey + "&coordsys=gps&locations=" + longitude + "," + latitude);
//                planActionRecordOsd.setLongitude(longitude);
//                planActionRecordOsd.setLatitude(latitude);
//                planActionRecordOsd.setHeight(pushMqVo.getData().getBigDecimal("height"));
//                planActionRecordOsd.setCreateTime(new Date(pushMqVo.getData().getLong("CreateTime")));
//
//                planActionRecordOsdMapper.insertPlanActionRecordOsd(planActionRecordOsd);
//                break;
//            case SERVICES_DRONE_STORAGE :
//                /***
//                 * 图片录像地址
//                 */
//                PlanActionRecordMedia planActionRecordMedia = new PlanActionRecordMedia();
//                planActionRecordMedia.setDroneSn(pushMqVo.getSn());
//                planActionRecordMedia.setRecordId(pushMqVo.getData().getLong("RecordId"));
//                planActionRecordMedia.setMediaType(pushMqVo.getData().getInteger("mediaType"));
//                planActionRecordMedia.setMediaUrl(pushMqVo.getData().getString("mediaUrl"));
//                planActionRecordMedia.setMediaSize(pushMqVo.getData().getLongValue("mediaSize", 0L));
//                planActionRecordMedia.setLongitude(pushMqVo.getData().getBigDecimal("longitude"));
//                planActionRecordMedia.setLatitude(pushMqVo.getData().getBigDecimal("latitude"));
//                planActionRecordMedia.setHeight(pushMqVo.getData().getBigDecimal("height"));
//                planActionRecordMedia.setCreateTime(new Date(pushMqVo.getData().getLong("CreateTime")));
//
//                planActionRecordMediaMapper.insertPlanActionRecordMedia(planActionRecordMedia);
//                break;
//            default:
//
//                break;
//        }
//    }

    public void osdSuf(CommonTopic readValue, String sn) {
        
    }

    public void thingStatus(CommonTopic readValue, String sn) {
        //直播能力live_capacity
        if(readValue.getData().containsKey("live_capacity")){

            LiveCapacity d = JSON.parseObject(readValue.getData().getString("live_capacity"), LiveCapacity.class);
            System.out.println("");
        }



    }
}
